from flask import Flask, request, jsonify
import json
import os
import time
import random
from uuid import uuid4  # 新增导入

app = Flask(__name__)

# 配置CORS支持（解决跨域问题）
from flask_cors import CORS
CORS(app)

# 定义数据存储目录
DATA_DIR = 'received_data'
os.makedirs(DATA_DIR, exist_ok=True)

@app.route('/api/save_location', methods=['POST'])
def save_location():
    try:
        # 解析前端发送的JSON数据
        data = request.get_json()
        print(data)
        if not data or 'latitude' not in data or 'longitude' not in data:
            return jsonify({"error": "Invalid data format"}), 400

        # 构建文件名（时间戳+UUID）
        filename = f"{DATA_DIR}/location_{int(time.time())}_{uuid4().hex}.json"  # 修改文件名生成逻辑

        # 将数据保存到本地文件
        with open(filename, 'w', encoding='utf-8') as f:
            json.dump(data, f, ensure_ascii=False)

        return jsonify({"status": "success", "filename": filename}), 200

    except Exception as e:
        # 捕获所有异常并返回错误信息
        return jsonify({"error": str(e)}), 500

if __name__ == '__main__':
    app.run(host='0.0.0.0',port=80,debug=True)